package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper,Clazz> implements ClazzService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private ClazzMapper clazzMapper;
    @Override
    public PageResult<Clazz> getList(ClazzQueryParam clazzQueryParam) {
        Page<Clazz> getPage = new Page<>(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        LambdaQueryWrapper<Clazz> clazzLambdaQueryWrapper = new LambdaQueryWrapper<Clazz>()
                .like(Clazz::getName,clazzQueryParam.getName())
                .between(Clazz::getBeginDate ,clazzQueryParam.getBegin(),clazzQueryParam.getEnd());


        Page<Clazz> page = this.page(getPage );
        List<Clazz> records = getPage.getRecords();
        records.forEach(clazz -> {
            //判断开课时间是否大于当前时间
            if (clazz.getBeginDate().isBefore(ChronoLocalDate.from(LocalDateTime.now()))){
                clazz.setStatus("开课");
            }else if (clazz.getBeginDate().isAfter(ChronoLocalDate.from(LocalDateTime.now()))){
                clazz.setStatus("未开课");
            }else {
                clazz.setStatus("正在开课");
            }
            Integer masterId = clazz.getMasterId();


            if (masterId != null){
                Emp emp = empMapper.selectById(masterId);
                if (emp != null){
                    clazz.setMasterName(emp.getName());
                }else {
                    clazz.setMasterName("");
                }
            }



        });
        return new PageResult<>(page.getTotal(),page.getRecords());
    }

    @Override
    public void saveList(Clazz clazz) {
        // 新增班主任校验
        Integer masterId = clazz.getMasterId();
        if (masterId != null) {
            Emp emp = empMapper.selectById(masterId);
            if (emp == null) {
                throw new RuntimeException("班主任ID不存在");
            }
        }

        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        this.save(clazz);
    }

    @Override
    public Clazz getId(Integer id) {
        return clazzMapper.selectById(id);
    }
}
